package com.fingard.dsp.bank.directbank.icbc02;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IImportLC;
import com.fingard.dsp.bank.reqrespobj.importlc.ReqImportLCQry;
import com.fingard.dsp.bank.reqrespobj.importlc.detail.RetAtsImportLCQry;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ICBC02ImportLC extends ICBC02Base implements IImportLC{
    @Override
    public RetAtsImportLCQry issueApply(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICOPN";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            String defPayCla = "";
            String mixPayCla = "";
            while (reqImportLC.readRecord()) {
                if(reqImportLC.detail.payType.equals("D")) {
                    defPayCla = reqImportLC.detail.defOrMixPayCla;
                }else if(reqImportLC.detail.payType.equals("M")){
                    mixPayCla = reqImportLC.detail.defOrMixPayCla;
                }
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("AppDate", reqImportLC.detail.appDate);
                xmlWriter.writeElementString("AppAddr", reqImportLC.detail.appAddr);
                xmlWriter.writeElementString("AppAccNo", reqImportLC.detail.appAccNo);
                xmlWriter.writeElementString("FeeAccNo", reqImportLC.detail.feeAccNo);
                xmlWriter.writeElementString("ContractNo", reqImportLC.detail.contractNo);
                xmlWriter.writeElementString("AppType", reqImportLC.detail.appType);
                xmlWriter.writeElementString("AdvNameAddr", reqImportLC.detail.advNameAddr);
                xmlWriter.writeElementString("BenNameAddr", reqImportLC.detail.benNameAddr);
                xmlWriter.writeElementString("LCType", "");//信用证形式 I：不可撤销IS：不可撤销备用IT：不可撤销的转让R:可撤销RT：可撤销转让S：可撤销备用TS：不可撤销反式备用
                xmlWriter.writeElementString("LCexpiryDate", reqImportLC.detail.LCexpiryDate);
                xmlWriter.writeElementString("ExpiryPlace", reqImportLC.detail.expiryPlace);
                xmlWriter.writeElementString("LCCurrCode", reqImportLC.detail.LCCurrCode);
                xmlWriter.writeElementString("LCAmt", reqImportLC.detail.LCAmt);
                xmlWriter.writeElementString("AmtUpFloat", reqImportLC.detail.amtUpFloat);//开证金额向上浮动
                xmlWriter.writeElementString("AmtDownFloat", reqImportLC.detail.amtDownFloat);//开证金额向下浮动
                xmlWriter.writeElementString("LCMaxAmtDes", "");//信用证最高限额描述
                xmlWriter.writeElementString("LCMaxAmt", "");//信用证最高限额
                xmlWriter.writeElementString("AddiAmt", "");//附加金额
                xmlWriter.writeElementString("SpecBankType",  reqImportLC.detail.specBankType);
                xmlWriter.writeElementString("SpecBankSwft",  reqImportLC.detail.specBankSwft);
                xmlWriter.writeElementString("SpecBankNameAddr",  reqImportLC.detail.specBankNameAddr);
                xmlWriter.writeElementString("SpecBankOpt",  "");//兑付指定银行选项
                xmlWriter.writeElementString("PayType",  reqImportLC.detail.payType);
                xmlWriter.writeElementString("DraftPayType",  "");//汇票付款类型
                xmlWriter.writeElementString("DraftPayDays",  reqImportLC.detail.draftPayDays);
                xmlWriter.writeElementString("DraftPct", reqImportLC.detail.draftPct);
                xmlWriter.writeElementString("DraftDes", "");//汇票描述
                xmlWriter.writeElementString("TermDes", "");//期限详述
                xmlWriter.writeElementString("DraftBankSwft", "");//汇票付款人
                xmlWriter.writeElementString("DefPayCla", defPayCla);//迟期付款条款
                xmlWriter.writeElementString("MixPayCla", mixPayCla);//混合付款条款
                xmlWriter.writeElementString("PartShipCla", "");//分批装运条款
                xmlWriter.writeElementString("TranShipCla", "");//转运条款
                xmlWriter.writeElementString("LoadSpot", reqImportLC.detail.loadSpot);
                xmlWriter.writeElementString("DestSpot", reqImportLC.detail.destSpot);
                xmlWriter.writeElementString("LoadPort", reqImportLC.detail.loadSpot);
                xmlWriter.writeElementString("UnLoadPort", reqImportLC.detail.unLoadPort);
                xmlWriter.writeElementString("ApplyRule", "");//适用规则
                xmlWriter.writeElementString("LatestDate", reqImportLC.detail.latestDate);
                xmlWriter.writeElementString("Shipper", "");//装运期
                xmlWriter.writeElementString("GoodDesc", reqImportLC.detail.goodDesc);
                xmlWriter.writeElementString("BillCla", reqImportLC.detail.billCla);
                xmlWriter.writeElementString("AddiCondiCla", reqImportLC.detail.addiCondiCla);
                xmlWriter.writeElementString("FeeCla", reqImportLC.detail.feeCla);
                xmlWriter.writeElementString("PresPeriod", reqImportLC.detail.presPeriod);
                xmlWriter.writeElementString("CfmInstype", reqImportLC.detail.cfmInstype);
                xmlWriter.writeElementString("Notes", reqImportLC.detail.memo);
                xmlWriter.writeElementString("PersonName", reqImportLC.detail.contactPerson);
                xmlWriter.writeElementString("TelePhoneNo", reqImportLC.detail.contactNum);
                //xmlWriter.writeElementString("QFHSerial", reqImportLC.reqHeader.transSeqID);
                //xmlWriter.writeElementString("CorpBusCode", reqImportLC.reqHeader.transSeqID);
                //xmlWriter.writeElementString("PRODID", "123");
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(),true);
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsImportLCQry issueApplyEdit(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICAME";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            while (reqImportLC.readRecord()) {
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("AppDate", reqImportLC.detail.appDate);
                xmlWriter.writeElementString("LCNo", reqImportLC.detail.LCNo);
                xmlWriter.writeElementString("AppType", reqImportLC.detail.appType);
                xmlWriter.writeElementString("AdvNameAddr", reqImportLC.detail.advNameAddr);
                xmlWriter.writeElementString("BenNameAddr", reqImportLC.detail.benNameAddr);
                xmlWriter.writeElementString("ModiTimes", "");//修改次数
                xmlWriter.writeElementString("AddAmt", "");//增加金额
                xmlWriter.writeElementString("SubAmt", "");//减少金额
                xmlWriter.writeElementString("LCCurrCode", reqImportLC.detail.LCCurrCode);
                xmlWriter.writeElementString("LCAmt", reqImportLC.detail.LCAmt);
                xmlWriter.writeElementString("AmtUpFloat", reqImportLC.detail.amtUpFloat);
                xmlWriter.writeElementString("AmtDownFloat", reqImportLC.detail.amtDownFloat);
                xmlWriter.writeElementString("LCMaxAmtDes", "");
                xmlWriter.writeElementString("LCMaxAmt", "");
                xmlWriter.writeElementString("AddiAmt", "");
                xmlWriter.writeElementString("LoadSpot", reqImportLC.detail.loadSpot);
                xmlWriter.writeElementString("DestSpot", reqImportLC.detail.destSpot);
                xmlWriter.writeElementString("LoadPort", reqImportLC.detail.loadSpot);
                xmlWriter.writeElementString("UnLoadPort", reqImportLC.detail.unLoadPort);
                xmlWriter.writeElementString("LatestDate", reqImportLC.detail.latestDate);
                xmlWriter.writeElementString("Shipper", "");
                xmlWriter.writeElementString("LCexpiryDate", reqImportLC.detail.LCexpiryDate);
                xmlWriter.writeElementString("AmendDes", "");//新修改描述
                xmlWriter.writeElementString("ToBenInf", "");//给收报人信息
                xmlWriter.writeElementString("FeePayer", "");//1－境内 申请人承担2－境外 受益人承担
                xmlWriter.writeElementString("Notes", reqImportLC.detail.memo);
                xmlWriter.writeElementString("PersonName", reqImportLC.detail.contactPerson);
                xmlWriter.writeElementString("TelePhoneNo", reqImportLC.detail.contactNum);
                xmlWriter.writeElementString("DraftPayType",  "");//汇票付款类型M、P、A、D
                xmlWriter.writeElementString("DraftPct", reqImportLC.detail.draftPct);
                xmlWriter.writeElementString("DraftPayDays", "");
                xmlWriter.writeElementString("TermDes", "");//新期限详述
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsImportLCQry disConfirm(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICEDC";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            while (reqImportLC.readRecord()) {
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("LCNo", reqImportLC.detail.LCNo);
                xmlWriter.writeElementString("BRNo", reqImportLC.detail.BRNo);
                xmlWriter.writeElementString("BillCurrCode", reqImportLC.detail.billCurrCode);
                xmlWriter.writeElementString("BillAmt", reqImportLC.detail.billAmt);
                xmlWriter.writeElementString("AccDiffer", reqImportLC.detail.accDiffer);//是否接受不符点1.是2.否
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsImportLCQry orderHonour(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICACP";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            while (reqImportLC.readRecord()) {
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("BRNo", reqImportLC.detail.BRNo);
                xmlWriter.writeElementString("ComBillDate", reqImportLC.detail.comBillDate);//来单日期
                xmlWriter.writeElementString("PayDueDate", reqImportLC.detail.payDueDate);//付款到期日
                xmlWriter.writeElementString("PayTotalAmt", reqImportLC.detail.payTotalAmt);//付款总金额
                xmlWriter.writeElementString("PayCurrCode", reqImportLC.detail.payCurrCode);//付款总金额币种
                xmlWriter.writeElementString("AccNo", reqImportLC.detail.appAccNo);//结算出账账号
                xmlWriter.writeElementString("FeeAccNo", reqImportLC.detail.feeAccNo);//费用出账账号
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsImportLCQry orderHonourEdit(ReqImportLCQry reqImportLC) {
        return orderHonour(reqImportLC);
    }

    @Override
    public RetAtsImportLCQry orderPay(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICPAY";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            while (reqImportLC.readRecord()) {
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("PayType", reqImportLC.detail.payType);//付款类型D:延期M:混合N:议付A:承兑P:即时
                xmlWriter.writeElementString("BRNo", reqImportLC.detail.BRNo);
                xmlWriter.writeElementString("ComBillDate", reqImportLC.detail.comBillDate);//来单日期
                xmlWriter.writeElementString("ValueDate", reqImportLC.detail.valueDate);//起息日期
                xmlWriter.writeElementString("PayCurrCode", reqImportLC.detail.payCurrCode);//付款总金额（币种）
                xmlWriter.writeElementString("PayTotalAmt", reqImportLC.detail.payTotalAmt);//付款总金额（金额）
                xmlWriter.writeElementString("Detail", reqImportLC.detail.chargeOffDetail);//出账明细
                xmlWriter.writeElementString("FeeAccNo", reqImportLC.detail.feeAccNo);//费用账号
                xmlWriter.writeElementString("Notes", reqImportLC.detail.memo);//备注
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsImportLCQry dishonor(ReqImportLCQry reqImportLC) {
        return  chargeBackApply(reqImportLC);
    }

    @Override
    public RetAtsImportLCQry chargeBackApply(ReqImportLCQry reqImportLC) {
        RetAtsImportLCQry retAts = new RetAtsImportLCQry(reqImportLC.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = reqImportLC.reqHeader.transSeqID;
            bnkTransCode = "LICRTN";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.0.1";
            Date date = new Date();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            while (reqImportLC.readRecord()) {
                messageDeal(xmlWriter,reqImportLC,date);
                xmlWriter.writeElementString("AppDate", reqImportLC.detail.appDate);
                xmlWriter.writeElementString("ComBillDate", reqImportLC.detail.comBillDate);//来单日期
                xmlWriter.writeElementString("BRNo", reqImportLC.detail.BRNo);
                xmlWriter.writeElementString("BillCurrCode", reqImportLC.detail.billCurrCode);
                xmlWriter.writeElementString("BillAmt", reqImportLC.detail.billAmt);
                xmlWriter.writeElementString("PersonName", reqImportLC.detail.contactPerson);
                xmlWriter.writeElementString("TelePhoneNo", reqImportLC.detail.contactNum);
                xmlWriter.writeElementString("RejDate", reqImportLC.detail.rejDate);
                xmlWriter.writeElementString("RejCur", reqImportLC.detail.rejCur);
                xmlWriter.writeElementString("RejAmt", reqImportLC.detail.rejAmt);
                xmlWriter.writeElementString("ReqReserved1", "");
                xmlWriter.writeElementString("ReqReserved2", "");
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            returnATS(tmpStrRet,retAts);
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        retAts.writeEnd();
        return retAts;
    }

    public void messageDeal(XmlTextWriter xmlWriter,ReqImportLCQry reqImportLC,Date date) throws Exception{
        xmlWriter.writeElementString("CorpDate", Format.Date8Format.format(date));
        xmlWriter.writeElementString("CorpTime", Format.Time6Format.format(date));
        xmlWriter.writeElementString("BankDate", "");
        xmlWriter.writeElementString("BankTime", "");
        xmlWriter.writeElementString("HeadCIS", bankFront.org);
        xmlWriter.writeElementString("BankCompanyId", getBankConfig().getValueAsString("bankCompanyId"));//银行公司编号 todo
        xmlWriter.writeElementString("BankBchCode", getBankConfig().getMapValueByKey("ICBCAreaCode",reqImportLC.detail.bankBchNo));
        xmlWriter.writeElementString("BankBchNo", getBankConfig().getMapValueByKey("ICBCNetNo",reqImportLC.detail.bankBchNo));
        xmlWriter.writeElementString("BankOrgCode", getBankConfig().getMapValueByKey("ICBCAreaCode",reqImportLC.detail.bankOrgNo));
        xmlWriter.writeElementString("BankOrgNo", getBankConfig().getMapValueByKey("ICBCNetNo",reqImportLC.detail.bankOrgNo));
        xmlWriter.writeElementString("Remark", reqImportLC.detail.usage);
        xmlWriter.writeElementString("AuthExpiryDate", reqImportLC.detail.authExpiryDate);
        xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(date));
        xmlWriter.writeElementString("CorpInCode", getBankConfig().getValueAsString("corpInCode"));//交易集团编号 todo;
    }

    public void returnATS(String[] tmpStrRet,RetAtsImportLCQry retAts) throws Exception{
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();

            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                if (isActiveRetCode(tmpRetCode)) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpRetMsg;
                    //0：提交成功等待银行处理1：授权成功等待银行处理2：待一次授权3：待二次授权4：等待银行答复6：发送后台失败7：发送后台成功9：发送后台可疑
                    //10：授权拒绝11：账务处理成功12：账务处理失败20：未核对21：正在处理22：插入临时表成功23：插入正式表成功26：文件解析成功27：文件不存在29：核对有误（如文件格式有误等）
                    retAts.transState = tmpRetCode + "+" + tmpBkReader.getFirstText("/CMS/eb/out/Result");
                    retAts.payInfoCode = retAts.transState;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpRetMsg;
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSbMsg.toString();
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpStrRet[1];
        }
    }

}
